package com.ruoyi.common.utils.ps2;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ImageProcessor {
    // 配置参数
    private static final String EDITED_FOLDER = "J:\\BaiduNetdiskDownload\\提交新片场\\202510-11号数据\\码诚提交-20250810-367组-质检-8.13-合格355-不合格12-总量367\\码诚提交-20050810-354组返367"
            +"\\处理图";
    private static final String DISQUALIFIED_FOLDER = EDITED_FOLDER+"\\不合格";
    private static final int MIN_RESOLUTION = 2048;
    private static final long MIN_FILE_SIZE = 1024 * 1024; // 1MB

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        try {
            System.out.println("开始处理编辑文件夹中的图片...");
            System.out.println("使用并行处理优化，线程数: " + getThreadCount());

            // 1. 确保不合格图片目录存在
            createDirectoryIfNotExists(DISQUALIFIED_FOLDER);

            // 2. 处理编辑文件夹中的图片（移动不合格图片）
            int disqualifiedCount = processEditedFolder();
            System.out.println("\n检测到 " + disqualifiedCount + " 张图片不符合要求");

            long duration = System.currentTimeMillis() - startTime;
            System.out.printf("处理完成！耗时: %.2f 秒%n", duration / 1000.0);
        } catch (Exception e) {
            System.err.println("处理过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 获取合适的线程数量 (CPU核心数 * 1.5)
     */
    private static int getThreadCount() {
        int cores = Runtime.getRuntime().availableProcessors();
        return Math.max(2, (int) (cores * 1.5)); // 至少2个线程
    }

    /**
     * 创建目录（如果不存在）
     */
    private static void createDirectoryIfNotExists(String path) {
        File dir = new File(path);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                System.out.println("创建目录: " + path);
            } else {
                System.err.println("无法创建目录: " + path);
            }
        }
    }

    /**
     * 并行处理编辑文件夹中的图片
     */
    private static int processEditedFolder() {
        File editedDir = new File(EDITED_FOLDER);
        File[] files = editedDir.listFiles();

        if (files == null || files.length == 0) {
            System.err.println("编辑文件夹中没有文件或路径错误: " + EDITED_FOLDER);
            return 0;
        }

        // 创建线程池
        int threadCount = getThreadCount();
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);
        List<Future<Boolean>> futures = new ArrayList<>();
        AtomicInteger disqualifiedCount = new AtomicInteger(0);
        AtomicInteger processedCount = new AtomicInteger(0);
        int totalFiles = files.length;

        // 进度跟踪
        ScheduledExecutorService progressScheduler = Executors.newSingleThreadScheduledExecutor();
        progressScheduler.scheduleAtFixedRate(() -> {
            int processed = processedCount.get();
            System.out.printf("\r处理进度: %d/%d (%.1f%%)", processed, totalFiles, (processed * 100.0 / totalFiles));
        }, 0, 500, TimeUnit.MILLISECONDS);

        for (File imageFile : files) {
            if (isImageFile(imageFile)) {
                futures.add(executor.submit(() -> {
                    try {
                        // 优先检查文件大小（快速检查）
                        boolean belowFileSize = isBelowFileSize(imageFile);
                        boolean belowResolution = false;

                        // 仅当文件大小合格时才检查分辨率
                        if (!belowFileSize) {
                            belowResolution = isBelowResolution(imageFile);
                        }

                        if (belowResolution || belowFileSize) {
                            // 移动到不合格图片文件夹
                            if (moveToDisqualifiedFolder(imageFile)) {
                                disqualifiedCount.incrementAndGet();
                            }
                        }
                        return true;
                    } catch (Exception e) {
                        System.err.println("\n处理图片 '" + imageFile.getName() + "' 时出错: " + e.getMessage());
                        return false;
                    } finally {
                        processedCount.incrementAndGet();
                    }
                }));
            } else {
                processedCount.incrementAndGet();
            }
        }

        // 等待所有任务完成
        for (Future<Boolean> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                System.err.println("任务执行异常: " + e.getMessage());
            }
        }

        // 关闭线程池和进度跟踪
        executor.shutdown();
        progressScheduler.shutdown();

        return disqualifiedCount.get();
    }

    /**
     * 将图片移动到不合格文件夹
     */
    private static boolean moveToDisqualifiedFolder(File imageFile) {
        File disqualifiedDir = new File(DISQUALIFIED_FOLDER);
        Path source = imageFile.toPath();
        Path targetDir = disqualifiedDir.toPath();

        try {
            // 处理文件名冲突
            String fileName = imageFile.getName();
            Path target = targetDir.resolve(fileName);
            int counter = 1;

            while (Files.exists(target)) {
                String newName = getFileNameWithoutExtension(fileName) +
                        "_" + counter +
                        getFileExtension(fileName);
                target = targetDir.resolve(newName);
                counter++;
            }

            // 使用NIO移动文件（更高效）
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
            return true;
        } catch (IOException e) {
            System.err.println("\n移动文件失败: " + imageFile.getName() + " - " + e.getMessage());
            return false;
        }
    }

    // ===== 优化后的工具方法 =====
    private static boolean isImageFile(File file) {
        String name = file.getName().toLowerCase();
        return name.endsWith(".jpg") || name.endsWith(".jpeg") ||
                name.endsWith(".png") || name.endsWith(".gif") ||
                name.endsWith(".bmp") || name.endsWith(".webp");
    }

    private static String getFileNameWithoutExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
    }

    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex);
    }

    /**
     * 优化后的分辨率检查（使用ImageReader只读取元数据）
     */
    private static boolean isBelowResolution(File imageFile) throws IOException {
        try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) {
            if (iis == null) {
                throw new IOException("无法创建图像输入流: " + imageFile.getName());
            }

            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (!readers.hasNext()) {
                throw new IOException("不支持的图像格式: " + imageFile.getName());
            }

            ImageReader reader = readers.next();
            try {
                reader.setInput(iis);
                int width = reader.getWidth(reader.getMinIndex());
                int height = reader.getHeight(reader.getMinIndex());
                return width < MIN_RESOLUTION || height < MIN_RESOLUTION;
            } finally {
                reader.dispose();
            }
        }
    }

    private static boolean isBelowFileSize(File file) {
        return file.length() < MIN_FILE_SIZE;
    }
}